package view.swing;

import static util.Constants.RACK_SIZE;

import java.awt.CardLayout;
import java.awt.GridLayout;
import java.util.List;

import javax.swing.JPanel;

import model.events.RackEvent;
import model.iview.IRack;
import model.iview.ITile;
import view.IRackView;
import view.swing.tiles.Placeur;
import view.swing.tiles.TileDragDroppable;
import view.swing.tiles.TilePanel;
public class RackView implements IRackView {

	@SuppressWarnings("serial")
	private static class TileOnRack extends JPanel implements TileDragDroppable {

		private ITile tile = null;
		private TilePanel tp = null;
		private TileDragDroppable sourceDrop = null;

		public TileOnRack() {
			super();
			setLayout(new CardLayout());

		}

		public TileOnRack(ITile tile) {
			this();
			setTile(tile);
			addMouseListener(new Placeur());
		}

		private void setTile(ITile tile) {
			this.tile = tile;
			tp = new TilePanel(tile);
			this.add(tp, "Center");
			this.updateUI();
		}

		@Override
		public void clear() {
			this.removeAll();
			this.tile = null;
			this.updateUI();
		}

		@Override
		public ITile drag() {
			ITile tmp = this.tile;
			clear();
			return tmp;
		}

		@Override
		public void drop(ITile tile) {
			this.tile = tile;
			this.removeAll();
			setTile(tile);
		}

		@Override
		public AllowedState getAllowedState() {
			return AllowedState.BOTH;
		}

		@Override
		public TileDragDroppable getSource() {
			return sourceDrop;
		}

		@Override
		public boolean hasTileHere() {
			return tile != null;
		}

		@Override
		public void setSource(TileDragDroppable tileSourceDrop) {
			this.sourceDrop = tileSourceDrop;
		}

		@Override
		public ITile getTile() {
			return tile;
		}

		@Override
		public void setSelected(boolean selected) {
			if (selected) {
				tp.setSelected();
			} else {
				tp.setNormal();
			}
		}

	}

	private JPanel rackPanel = new JPanel();

	public RackView() {
		super();
	}

	public RackView(IRack rack) {
		this();
		buildRackPanel(rack.getITiles());
	}

	private void buildRackPanel(List<ITile> tiles) {
		rackPanel.removeAll();
		GridLayout layout = new GridLayout(1, 6);
		layout.setHgap(5);

		rackPanel.setLayout(layout);
		for (ITile t : tiles) {
			rackPanel.add(new TileOnRack(t));
		}
		for (int i = tiles.size(); i < RACK_SIZE; i++) {
			rackPanel.add(new TileOnRack());
		}
		rackPanel.updateUI();
	}

	public JPanel getPanel() {
		return rackPanel;
	}

	/* (non-Javadoc)
     * @see view.swing.IRackView#rackChanged(model.events.RackEvent)
     */
	@Override
	public void rackChanged(RackEvent event) {
		buildRackPanel(event.getNewRack().getITiles());
	}
	
	/* (non-Javadoc)
     * @see view.swing.IRackView#unselectAll()
     */
	public void unselectAll() {
	    Placeur.reset();
	}

}
